/*
 * =====================================================================================
 *
 *       Filename:  LinearList.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  11/05/2012 03:24:53 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Kjeldahl (), 
 *   Organization:  
 *
 * =====================================================================================
 */


#include "LinearList.h"

LinearList * initLinearList(elmType *p,int size){
	LinearList *L;
	L=malloc(sizeof(LinearList));
	L->size=size;

	if (p==NULL && size >0){
		L->data=malloc(sizeof(elmType)*size);
		L->used=0;
	}else if(p!=NULL&&size>0){
		L->data=malloc(sizeof(elmType)*size);
		memcpy(L->data,p,size*sizeof(elmType));
		L->used=size;
	}else{
		exit(EXIT_FAILURE);
	}
	return L;

}
int destroyLinearList(LinearList *L){

	free((L->data));
	free(L);
	return 1;

}

int emptyLinearList(LinearList *L){
	memset(L->data,0,sizeof(elmType)*L->size);
	L->used=0;
}

elmType delelement(LinearList *L,int index){

	elmType temp=L->data[index];	
	memmove(L->data+index,L->data+index+1,(L->used-index-1)*sizeof(elmType));
	memset(L->data+L->used-1,0,sizeof(elmType));
	L->used--;
	return temp;
}

void listAll(LinearList *L){
	int i=0;
	for(;i<L->size;i++)
		printf("%d==>%d\n",i,L->data[i]);
}
elmType locateList(LinearList *L,int index){
	if(index<L->used&&index>=0){
		return L->data[index];
	}else{
	printf("index muset between 0 and %d",L->used);
	
	}
}
int insertLinearList(LinearList *L,int index,elmType value){
	if(L->size==L->used){
//		printf("Please resize the list first\n");
		incrementList(L,L->size);
//		return -1;
	}

	if(index>=0&&index<L->used&&L->size>L->used){
		memmove(L->data+index+1,L->data+index,sizeof(elmType)*(L->used-index));
		L->data[index]=value;
		L->used++;
	}else if(index>L->used&&index<L->size){
		L->data[index]=value;
		L->used=index+1;
	}

	return 0;

}
int searchList(LinearList *L,elmType value){
	int i=0;
	for(;i<L->used;i++)
		if(L->data[i]==value)
			return i;
	return -1;
}
int incrementList(LinearList *L,int incresize){
	L->size+=incresize;

	if(incresize>0){
		elmType *temp=L->data;
		L->data=realloc(L->data,sizeof(elmType)*L->size);
		if(L==NULL){
		printf("Couldnt increase the size of List\n");
		L->data=temp;
		}
	}else{
	printf("must be a positive size\n");
	}
	//printf("used:%d\n",L->size);
	memset(L->data+L->used-1,0,(incresize)*sizeof(elmType));
	return 0;
}
int decrementList(LinearList *L,int decresize){
	L->size-=decresize;
	L->data=realloc(L->data,sizeof(elmType)*L->size);
	L->used=L->used>L->size ? L->size : L->used;
	return 0;

}
